using System;
using System.Collections.Generic;
using UnityEngine;

public class DemoETsCallCSharp : MonoBehaviour
{
    private string logString = "";
    // public delegate object CSFunc(params IntPtr[] args);
    private OpenHarmonyJSClass m_ohJSClass = null;
    private NapiCallbackFunc m_csFunc;
    private IntPtr m_NapiRef = IntPtr.Zero;
    private IntPtr m_GCHandle = IntPtr.Zero;

    public string Test()
    {
        // 注册接口
        if (m_ohJSClass == null)
            m_ohJSClass = new OpenHarmonyJSClass("ETSCallCS");

        Debug.Log("start test");
        logString += $"start test\n";
        m_csFunc = AddInCS;
        m_GCHandle = OpenHarmonyJSAPI.AcquireCallbackGCHandle(NapiCallback);
        // m_GCHandle = OpenHarmonyJSAPI.AcquireCallbackGCHandle2(AddInCS);
        IntPtr napiValue = OpenHarmonyJSAPI.CreateFunction(m_GCHandle);
        m_NapiRef = OpenHarmonyJSAPI.CreateNapiReference(napiValue);

        var funcObj = new OpenHarmonyJSObject(napiValue);
        m_ohJSClass.CallStatic("setAdd", funcObj);
        
        logString += $"call ts method testAdd(1, 2)\n";
        Debug.Log("call ts method testAdd(1, 2)");
        var ret = m_ohJSClass.CallStatic<int>("testAdd", 1, 2);
        logString += $"testAdd(1, 2)| return=[{ret}]\n";
        logString += "test done.\n";
        Debug.Log($"testAdd(1, 2)| return=[{ret}]");
        Debug.Log("test done.");
        return logString;
    }
    
    private NapiCallbackFunc NapiCallback(params IntPtr[] args)
    {
        // List<OpenHarmonyJSObject> jsObjArgs = new List<OpenHarmonyJSObject>();
        // for (int i = 0; i < args.Length; i++)
        // {
        //     jsObjArgs.Add(new OpenHarmonyJSObject(args[i]));
        // }

        Debug.Log("Enter NapiCallback");
        logString += "Enter NapiCallback\n";
        var ret = m_csFunc.Invoke(args);
        logString += $"NapiCallback| ret={ret}\n";
        Debug.Log($"NapiCallback| ret={ret}");
        return null;
    }

    public object AddInCS(params IntPtr[] args)
    {
        // OpenHarmonyJSObject ao = (OpenHarmonyJSObject)args[0];
        // OpenHarmonyJSObject bo = (OpenHarmonyJSObject)args[1];
        int a = (int)OpenHarmonyJSHelper.ConvertToCSharpValue(typeof(int), args[0]);
        int b = (int)OpenHarmonyJSHelper.ConvertToCSharpValue(typeof(int), args[1]);
        logString += $"\t[CS] AddInCS| a={a} b={b} a+b={a + b}\n";
        Debug.Log($"\t[CS] AddInCS| a={a} b={b} a+b={a + b}");
        return a + b;
    }
    
    
}
